import pickle,base64

from django.db import transaction
from django_redis import get_redis_connection

def merge_cookie_to_redis(user,cart_cookie,response):

    cookie_plain = pickle.loads(base64.b64decode(cart_cookie.encode())) #{1:{'count':3,'selected':false}}

    redis = get_redis_connection('cart')

    try:
        cart_id_count = redis.hgetall('cart_%s'%user.id)
    except Exception:
        raise  Exception('读取购物车数据失败')

    cart_redis = {}
    cart_selected = []
    for id,count in cart_id_count.items():
        cart_redis[int(id)] = int(count)

    for id in cookie_plain:
        cart_redis[id]=cookie_plain[id]['count']
        if cookie_plain[id]['selected']:
            cart_selected.append(id)

    try:
        pl = redis.pipeline()
        pl.hmset('cart_%s'%user.id,cart_redis)
        pl.sadd('cart_selected_%s'%user.id,*cart_selected)
        pl.execute()
    except Exception:
        raise Exception('购物车数据保存失败')

    response.delete_cookie('cart')

    return response



